package cn.tedu.charging.order.rabbitmq;



import cn.tedu.charging.order.config.RabbitMQConfig;
import cn.tedu.charging.order.dao.repository.OrderRepository;
import cn.tedu.charging.order.pojo.po.RabbitmqDeadPo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class RabbitMQConsumer {

    @Autowired
    private OrderRepository orderRepository;
    /**
     * 指定队列 来消费信息 监听器
     * @param rabbitmqDeadPo 已经反序列化了的数据
     * @param message
     * @param channel
     */
    @RabbitListener(queues = RabbitMQConfig.DEAD_LETTER_QUEUE_NAME,ackMode = "MANUAL")
    public void consumeChargingQueue(RabbitmqDeadPo rabbitmqDeadPo, Message message, Channel channel){

        log.debug("死信队列消息: msg: {}, message: {}, channel: {}", rabbitmqDeadPo, message, channel);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            // 更新订单状态
            Integer i = orderRepository.updateStatusFromDead(rabbitmqDeadPo.getOrderNo());
            if (i == 1) {
                channel.basicAck(deliveryTag, false);  // 只确认当前消息
                log.debug("订单状态异常 已更新为异常");
            } else {
                log.warn("订单状态更新失败，消息未确认");
                channel.basicNack(deliveryTag, false, true);  // 拒绝并重新入队
            }
        } catch (IOException e) {
            log.error("消息确认失败", e);
            try {
                channel.basicNack(deliveryTag, false, true);  // 失败时拒绝并重新入队
            } catch (IOException ioException) {
                throw new RuntimeException("消息拒绝失败", ioException);
            }
        }
    }

}
